package com.moli.iov.sys.remote.impl;

import com.moli.iov.exception.BusinessException;
import com.moli.iov.model.dto.req.PageExtend;
import com.moli.iov.rest.RestResponse;
import com.moli.iov.sys.constants.Constant;
import com.moli.iov.sys.enums.RoleStatusEnum;
import com.moli.iov.sys.enums.RoleTypeEnum;
import com.moli.iov.sys.enums.UserTypeEnum;
import com.moli.iov.sys.model.dto.req.PermissionDto;
import com.moli.iov.sys.model.dto.req.RoleDto;
import com.moli.iov.sys.model.dto.req.RolePermissionDto;
import com.moli.iov.sys.model.po.Permission;
import com.moli.iov.sys.model.po.Role;
import com.moli.iov.sys.model.po.RolePermission;
import com.moli.iov.sys.remote.ICompanyRemoteService;
import com.moli.iov.sys.remote.IRoleThirdRemoteService;
import com.moli.iov.sys.service.IPermissionService;
import com.moli.iov.sys.service.IRolePermissionService;
import com.moli.iov.sys.service.IRoleService;
import com.moli.iov.util.CommonUtils;
import com.moli.iov.util.ValidationUtils;
import java.util.ArrayList;
import java.util.List;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * <p>
 * 角色业务  第三方调用
 * </p>
 *
 * @author zql
 * @since 2019/9/21 13:56
 */
@Slf4j
@Service(group = "${service.group}")
public class RoleThirdRemoteServiceImpl implements IRoleThirdRemoteService {

  @Autowired
  private ICompanyRemoteService companyRemoteService;

  @Autowired
  private IRoleService roleService;

  @Autowired
  private IRolePermissionService rolePermissionService;

  @Autowired
  private IPermissionService permissionService;

  /**
   *
   * 查询角色列表--下拉框
   *
   * @param roleDto
   * @return
   */
  @Override
  public RestResponse<List<Role>> listRole(RoleDto roleDto) {

    listRoleValid(roleDto);

    RoleDto roleDtoQuery = new RoleDto();
    roleDtoQuery.setCompanyId(roleDto.getCompanyId());
    roleDtoQuery.setStatus(RoleStatusEnum.ENABLED.getFlag());

    return RestResponse.success(roleService.listRole(roleDtoQuery));
  }

  /**
   * 查询角色列表 参数校验
   * @param roleDto
   */
  private void listRoleValid(RoleDto roleDto){

    ValidationUtils.restResponseValidate(roleDto, RoleDto.ListRole.class);

    companyRemoteService.companyValid(roleDto.getCompanyId());
  }

  /**
   *
   * 分页查询角色列表
   *
   * @param roleDto
   * @return
   */
  @Override
  public RestResponse<PageExtend<Role>> listRoleOfPage(RoleDto roleDto) {

    listRoleOfPageValid(roleDto);

    RoleDto roleDtoQuery = new RoleDto();
    roleDtoQuery.setCompanyId(roleDto.getCompanyId());
    roleDtoQuery.setStatus(roleDto.getStatus());
    roleDtoQuery.setPageNum(roleDto.getPageNum());
    roleDtoQuery.setPageSize(roleDto.getPageSize());
    roleDtoQuery.setRoleName(roleDto.getRoleName());

    return RestResponse.success(roleService.listRoleOfPage(roleDtoQuery));
  }

  /**
   * 分页查询角色列表 参数校验
   * @param roleDto
   */
  public void listRoleOfPageValid(RoleDto roleDto) {

    ValidationUtils.restResponseValidate(roleDto, RoleDto.ListRoleOfPage.class);
    companyRemoteService.companyValid(roleDto.getCompanyId());
  }

  /**
   * 增加角色
   * @param roleDto
   * @return
   */
  @Override
  public RestResponse saveRole(RoleDto roleDto) {

    roleDto.setRoleType(RoleTypeEnum.COMPANY.getFlag());
    saveRoleValid(roleDto);

    Long num = roleService.saveRole(roleDto);
    if(num <= 0){
      return RestResponse.failure("添加失败");
    }

    return RestResponse.success();
  }

  /**
   * 增加角色 参数校验
   * @param roleDto
   */
  private void saveRoleValid(RoleDto roleDto){

    ValidationUtils.restResponseValidate(roleDto, RoleDto.SaveRole.class);
    companyRemoteService.companyValid(roleDto.getCompanyId());
    RoleDto roleDtoQ = new RoleDto();
    roleDtoQ.setCompanyId(roleDto.getCompanyId());
    roleDtoQ.setPerfectRoleName(roleDto.getRoleName());
    List<Role> roles = roleService.listRole(roleDtoQ);
    if(roles != null && !roles.isEmpty()){
      throw new BusinessException("角色名称已存在");
    }
  }

  /**
   * 修改角色
   * @param roleDto
   * @return
   */
  @Override
  public RestResponse updateRoleByRoleId(RoleDto roleDto) {
    updateRoleByRoleIdValid(roleDto);

    Role role = new Role();
    CommonUtils.copyProperties(roleDto, role);
    int num = roleService.updateRoleByRoleId(role);

    if(num <= 0){
      return RestResponse.failure("修改失败");
    }
    return RestResponse.success();
  }

  /**
   * 修改角色 参数校验
   * @param roleDto
   */
  private void updateRoleByRoleIdValid(RoleDto roleDto){

    ValidationUtils.restResponseValidate(roleDto, RoleDto.UpdateRoleByRoleId.class);
    companyRemoteService.companyValid(roleDto.getCompanyId());

    Role roleByRoleId = roleService.getRoleByRoleId(roleDto.getRoleId());
    if(roleByRoleId == null){
      throw new BusinessException("角色id不存在");
    }

    RoleDto roleDtoQuery = new RoleDto();
    roleDtoQuery.setPerfectRoleName(roleDto.getRoleName());
    roleDtoQuery.setNeRoleId(roleDto.getRoleId());
    roleDtoQuery.setCompanyId(roleDto.getCompanyId());

    List<Role> roles = roleService.listRole(roleDtoQuery);
    if(roles != null && !roles.isEmpty()){
      throw new BusinessException("角色名称已经存在");
    }
  }

  /**
   * 设置权限
   * @param roleDto
   * @return
   */
  @Override
  public RestResponse setPermission(RoleDto roleDto) {

    setPermissionThirdValid(roleDto);

    rolePermissionService.deleteRolePermission(roleDto.getRoleId());

    List<RolePermission> rolePermissions =
        assembleRolePermissions(roleDto.getRoleId(), roleDto.getPermissionIds());

    if(!rolePermissionService.saveBatchRolePermission(rolePermissions)){
      return RestResponse.failure("设置权限失败");
    }
    return RestResponse.success();
  }

  /**
   * 设置权限 参数校验
   * @param roleDto
   */
  private void setPermissionThirdValid(RoleDto roleDto){

    ValidationUtils.restResponseValidate(roleDto, RoleDto.SetPermissionThird.class);
    companyRemoteService.companyValid(roleDto.getCompanyId());
  }

  /**
   * 组装 角色权限集合
   * @param roleId
   * @param permissionIds
   * @return
   */
  private List<RolePermission> assembleRolePermissions(Long roleId, List<Long> permissionIds){
    List<RolePermission> rolePermissions = new ArrayList<>();
    permissionIds.forEach(peId ->
        rolePermissions.add(new RolePermission(roleId, peId)));
    return rolePermissions;
  }

  /**
   * 权限详情
   * @param roleDto
   * @return
   */
  @Override
  public RestResponse<RolePermissionDto> getRolePermissions(RoleDto roleDto) {

    getRolePermissionsValid(roleDto);

    PermissionDto permissionDto = new PermissionDto();
    permissionDto.setPid(Constant.PID_DEFAULT);
    permissionDto.setUserType(UserTypeEnum.COMPANY.getFlag());
    List<Permission> permissions = permissionService.listPermission(permissionDto);

    List<RolePermission> rolePermissions = rolePermissionService.listRolePermission(roleDto);
    List<Long> permissionR = new ArrayList<>();
    rolePermissions.forEach(permission-> permissionR.add(permission.getPermissionId()));

    return RestResponse.success(new RolePermissionDto(permissionR, permissions));
  }

  /**
   * 权限列表 -- 设置权限 参数校验
   * @param roleDto
   */
  private void getRolePermissionsValid(RoleDto roleDto){

    ValidationUtils.restResponseValidate(roleDto, RoleDto.GetRolePermissions.class);
    companyRemoteService.companyValid(roleDto.getCompanyId());
  }

  /**
   * 查询角色数量
   * @param roleDto
   * @return
   */
  @Override
  public RestResponse<Integer> getRoleCount(RoleDto roleDto) {
    ValidationUtils.restResponseValidate(roleDto, RoleDto.GetRoleCount.class);
    roleDto.setCompanyId(roleDto.getCompanyId());
    return RestResponse.success(roleService.getRoleCount(roleDto));
  }
}
